package com.jason.core.config.security;

import com.jason.core.config.security.service.JwtUserDetailsServiceImpl;
import com.jason.core.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private JwtUserDetailsServiceImpl userDetailsService;

    @Value("${jwt.exceptUrl}")
    private String exceptUrl;


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 用户名密码认证方法
     * @param authenticationManagerBuilder
     * @throws Exception
     */
    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                // 设置UserDetailsService
                .userDetailsService(userDetailsService);
    }

    /**
     * 装载BCrypt密码编码器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
        return new JwtAuthenticationTokenFilter();
    }

    /**
     * token请求授权
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 添加JWT filter
        httpSecurity
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);  //将token验证添加在密码验证前面

        httpSecurity
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()

                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()//未授权处理

                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()


                .authorizeRequests()

                // 对于获取token的rest api要允许匿名访问
                .antMatchers(exceptUrl).permitAll()
                //不拦截跨域请求
//                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // 允许对于网站静态资源的无授权访问
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/export/**",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/*/api-docs",
                        "/druid/*"
                ).permitAll()
                // 对于获取token的rest api要允许匿名访问
//                .antMatchers("/auth/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
//                .anyRequest().authenticated()

                /*.antMatchers("/login").permitAll()
                .anyRequest().authenticated()*/

//                .antMatchers("/*/api-docs").permitAll()
//                .anyRequest().authenticated()
//
//                .antMatchers("/swagger-resources/**").permitAll()
//                .anyRequest().authenticated()
//
//                .antMatchers("/swagger**").permitAll()
//                .anyRequest().authenticated()
//
//                .antMatchers("/webjars/**").permitAll()

                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();


        // 禁用缓存
        httpSecurity.headers().cacheControl();
        /*http.authorizeRequests()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login")
                //设置默认登录成功跳转页面
                .defaultSuccessUrl("/index").failureUrl("/login?error").permitAll()
                .and()
                //开启cookie保存用户数据
                .rememberMe()
                //设置cookie有效期
                .tokenValiditySeconds(60 * 60 * 24 * 7)
                //设置cookie的私钥
                .key("")
                .and()
                .logout()
                //默认注销行为为logout，可以通过下面的方式来修改
                .logoutUrl("/logout")
                //设置注销成功后跳转页面，默认是跳转到登录页面
                .logoutSuccessUrl("")
                .permitAll();*/
    }


//    @Overridep
//    public void configure(WebSecurity web) throws Excetion {
//        web.ignoring().mvcMatchers("/static/**", "/*/api-docs", "/swagger-resources/**", "/swagger**", "/webjars/**", "/druid/*");//权限控制需要忽略所有静态资源，不然登录页面未登录状态无法加载css等静态资源
////        .antMatchers("/*/api-docs")//权限控制需要忽略所有静态资源，不然登录页面未登录状态无法加载css等静态资源
////        .antMatchers("/swagger-resources/**")//权限控制需要忽略所有静态资源，不然登录页面未登录状态无法加载css等静态资源
////        .antMatchers("/swagger**")//权限控制需要忽略所有静态资源，不然登录页面未登录状态无法加载css等静态资源
////        .antMatchers("/webjars/**");//权限控制需要忽略所有静态资源，不然登录页面未登录状态无法加载css等静态资源
//    }

    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        System.out.println(encoder.encode("1234"));
    }

}
